package com.wind.test;

import com.wind.entity.User;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JpaTest01_HelloWorld {

  public static void main(String[] args) {
    // persistence.xml 中 <persistence-unit name="JpaDemo" 的 name值
    String persistenceUnitName = "JpaDemo";

    // Key 必须是 persistence.xml 中的 name 值
    Map<String, Object> map = new HashMap<>();
    map.put("hibernate.show_sql", true);

    // 1.创建 EntitymanagerFactory
//    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName);
    /*
      Persistence 重载的方法 有两个参数：(String persistenceUnitName, Map properties)
        Map：可以修改 persistence.xml 配置文件中值 必须和配置文件中的 name 属性一致
     */
    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName, map);

    // 2.创建 EntityManager （类似于 Hibernate 的 SessionFactory）
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    // 3.开启事务
    EntityTransaction transaction = entityManager.getTransaction();
    transaction.begin();

    // 4.进行持久化操作
    User user = new User();
    user.setLastName("张三丰"); // 中文进数据库乱码了~~~
    user.setAge(5);
    user.setCreateTime(new Date());
    user.setBirth(new Date());

    entityManager.persist(user);

    // 5.提交事务
    transaction.commit();

    // 6.关闭 EntityManager
    entityManager.close();

    // 7.关闭 EntitymanagerFactory
    entityManagerFactory.close();
  }
}
